package com.baomidou.plugin.idea.mybatisx.advance.processor.clazz;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.plugin.idea.mybatisx.advance.problem.ProblemBuilder;
import com.baomidou.plugin.idea.mybatisx.advance.psi.MyLightFieldBuilder;
import com.baomidou.plugin.idea.mybatisx.advance.util.PsiClassUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.impl.light.LightElement;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * 生成常量
 * @author wanglei
 */
public class ConstantProcessor extends AbstractMPClassProcessor {

    private static final String CLASS_NAME = TableName.class.getName();

    public ConstantProcessor() {
        super(CLASS_NAME, PsiField.class);
    }

    @Override
    protected boolean validate(@NotNull PsiAnnotation psiAnnotation, @NotNull PsiClass psiClass, @NotNull ProblemBuilder builder) {
        boolean result = true;
        if (psiClass.isInterface() || psiClass.isAnnotationType()) {
            builder.addError("@Wrapperable is legal only on classes and enums");
            result = false;
        }
        return result;
    }

    protected <Psi extends PsiElement> void processIntern(@NotNull PsiClass psiClass, @NotNull PsiAnnotation psiAnnotation, @NotNull List<Psi> target) {
        Project project = psiClass.getProject();
        PsiManager manager = psiClass.getContainingFile().getManager();

        final PsiElementFactory psiElementFactory = JavaPsiFacade.getElementFactory(project);
        PsiType psiLoggerType = psiElementFactory.createTypeFromText("java.lang.String", psiClass);

        final PsiField[] fields = PsiClassUtil.collectClassFieldsIntern(psiClass);
        for (PsiField field : fields) {
            LightElement loggerField = new MyLightFieldBuilder(manager, field.getName().toUpperCase(), psiLoggerType)
                    .setHasInitializer(true)
                    .setContainingClass(psiClass)
                    .setModifiers(PsiModifier.FINAL, PsiModifier.STATIC, PsiModifier.PUBLIC);
            loggerField.setNavigationElement(psiAnnotation);
            PsiExpression initializer = psiElementFactory.createExpressionFromText(field.getName(), psiClass);
            ((MyLightFieldBuilder) loggerField).setInitializer(initializer);
            target.add((Psi) loggerField);
        }
    }
}
